import express from 'express'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import path from 'path'
// app.all('*', function(req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//     res.header("X-Powered-By",' 3.2.1');
//     next();
// });
import csshook from 'css-modules-require-hook/preset'
import assethook from 'asset-require-hook'
assethook({
    extensions: ['png'],
    limit: 8000
})

import React from 'react'
import {renderToString, renderToStaticMarkup} from 'react-dom/server'
import { Provider } from 'react-redux'
import {StaticRouter } from 'redux-thunk'
import { BrowserRouter, Router /*, Route, Routes*/ } from 'react-router-dom'
import { createStore, applyMiddleware, compose } from 'redux'
import reducers from '../src/reducer'
import thunk from 'redux-thunk'
import App from '../src/app'

// function App() {
//     return (
//         <div>
//             <p>ssr</p>
//             <p>imalsdf asdf asdf </p>
//         </div>
//     )
// }
// console.log(renderToString(<App></App>))

// "babel": {
//     "presets": [
//       "react-app"
//     ],
//     "plugins": [
//       [
//         "import",
//         {
//           "libraryName": "antd-mobile",
//           "style": "css"
//         }
//       ],
//       [
//         "@babel/plugin-proposal-decorators",
//         {
//           "legacy": true
//         }
//       ]
//     ]
//   },
// http + express(app) + socket.io

const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const model = require('./model')
const Chat = model.getModel('chat')
// io.set('transports', ['websocket', 'xhr-polling', 'jsonp-polling', 'htmlfile', 'flashsocket'])
// io.set('origins', '*:*')
// var io = require('socket.io')(server, {origins:'*:*'});
io.on('connection', socket => {
    // console.count('user login:')
    socket.on('sendmsg', data => {
        const {from, to, msg} = data
        const chatid = [from, to].sort().join('_')
        // console.log({data}, chatid)
        Chat.create({chatid, from, to, content: msg}, (err, doc) => {
            if(err) {
                console.log(err ,doc)
                return
            }
            io.emit('recvmsg', Object.assign({}, doc._doc))
        })
        // io.emit('recvmsg', data)
    })
})

const userRouter = require('./user')
// const { default: Chat } = require('../src/component/chat/chat')

app.use(cookieParser())
app.use(bodyParser.json())
app.use('/user', userRouter)

/**
 *  build & deploy
 */
// app.use((req, res, next) => {
//     if (req.url.startsWith('/user/') || req.url.startsWith('/static/')) {
//         return next()
//     }
//     console.log('PATH:', path.resolve('build/index.html'))
//     console.log(req.url)
//     const context = {}
//     const store = createStore(reducers, compose(applyMiddleware(thunk)))
//     // const store = createStore(reducer)
//     const markup = renderToString(
//         (<Provider store={store}>
//             {/* <BrowserRouter
//                 location={req.url}
//                 context={context}
//             > */}
//                 <App></App>
//             {/* </BrowserRouter> */}
//         </Provider>)
//     )
//     const htmRes = renderToString(<App></App>)
//     res.send(htmRes)
//     // return res.sendFile(path.resolve('build/index.html'))
// })
// app.use('/', express.static(path.resolve('build')))

/**
 * publish procedure
 * 1. purchase domain, dns deploy(dns to server IP);
 * 2. nginx reverse delegation
 * 3. pm2: node process management
 * 4. DB/express deploy;
 */

app.get('/', (req, res) => {
    res.send(`DB_URL = 'mongodb://127.0.0.1:27017/boss'`)
})

server.listen(9093, a => {
    console.log('Node app start at port 9093')
})
